// pages/goodsDetail/goodsDetail.js

var that,
  WxParse = require('../../wxParse/wxParse.js'),
  api = new(require('../../utils/api.js')),
  headimg = api.getimgurl(),
  app = getApp(),
  util = new(require('../../utils/util.js'));

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressid: -1,
    totalprice:0,
    totalscore:0,
    showchose: !1,
    isvip:!1,
    indicatorDots: true, //小点
    indicatorColor: "white", //指示点颜色
    activeColor: "#0094F3", //当前选中的指示点颜色
    autoplay: true, //是否自动轮播
    interval: 2000, //间隔时间
    duration: 500, //滑动时间
    circular: true,
    detail: '', //详情
    lbimg: '', //轮播图
    price: '', //价格
    stock: 0, // 库存,
    promotionprice: '', //促销价
    topimg: '',
    name: '',
    goodsunit: '',
    goodslist: [],
    count: 1,
    goodscount:0,// 商品数量
    price :0,// 总价格
    goodsnum:'',//  商品编号
    id:0,
    isscore:'F',
    speccont:'',
    indexsel:0,
    isretail:"",
    imgarr:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function(options) {
    that = this;
    console.log("!11111111111111")
    let address = wx.getStorageSync('address');
    // let postfee = wx.getStorageSync('postfee');
    // that.setData({postfee})
    
    // if (address) {
    //   that.setData({
    //     address: address.province + address.city + address.county + address.street,
    //     addressid: address.id
    //   })
    // }
    console.log(options,'goodsDetailgoodsDetailoptions');
    
    let {id , iscollect} =that.data,origuserinfo = wx.getStorageSync('userinfo')
    id=options.id,
    that.setData({id,origuserinfo},()=>{
     
      if (app.logininfo) {
        that.getdetail()
      } else {
        util.setwatcher(app, this.afterlogin)
      }
    })
 
  },
  afterlogin: {
    token: res => {
      that.getdetail()
    }
  },
  //跳转购物车
  addcar(){
    wx.switchTab({
      url: '../books/books',
    })
  },

 getdetail(){
  let appletname=app.logininfo.appletname,isconsumer=app.logininfo.user.type=='CONSUMER',usertype=app.logininfo.user.type
  wx.setNavigationBarTitle({
    title: appletname  || '小巴学堂',
  })
  wx.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
   wx.showLoading({
     title: '加载中',
   })
  let {id , iscollect,goodslist,count} =that.data
  api.getgoodsdetailbyid(id, res => {
    wx.hideLoading({
    })
    console.log(res,"resresres")
    if (res.data.issuccess == 1) {
      console.log(res.data, 'res.data')
      let { detail, price, stock, lbimg, name, promotionprice,goodsunit,topimg,goodssn,isretail,cid,id} = res.data.data
      price = (price / 100).toFixed(2)
      promotionprice = (promotionprice / 100).toFixed(2)
      detail = decodeURIComponent(detail);
      topimg = headimg + topimg
      let newdata = {promotionprice:res.data.data.promotionprice,thumbPicPath:res.data.data.topimg,goodsid:id,name}
      WxParse.wxParse('article', 'html', detail, that, 5);
      let imgurlarr = lbimg.split(","),
        imgarr = [],
        newdetail = ''
      imgurlarr.map((x, i) => {
        imgarr.push(headimg + x)
      })
      goodslist.push(newdata)
      that.setData({ isretail, imgarr, name,promotionprice, price,stock,goodsunit,topimg, 
        goodssn, data: res.data.data,cid ,goodslist})

    }
  })
 },
  tocart(){
    wx.navigateTo({
      url: '../cart/cart',
    })
  },
  replaceraw(content) {
     return  content.replace('rgb(', 'rgb').replace(new  RegExp('rgb', 'g'), "rgb(");
  },

  checkfreight() {
    wx.navigateTo({
      url: '../freight/freight',
    })
  },
  returnClassification() {
    console.log(111)
    wx.switchTab({
      url: '../classification/classification',
    })
  },
  returnIndex() {
    console.log(111)
    wx.switchTab({
      url: '../index/index',
    })
  },
  receivingAddress() {
    console.log(111)
    let {
      addressid
    } = this.data, url = "../address/address" + (addressid > 0 ? "?id=" + addressid : "");
    wx.navigateTo({
      url
    })
  },
  choicetap(){
    console.log(11)
    that.setData({
      showchose: !0,
      anim: 'sizewrap 0.3s'
    })
  },
  btntap(e) {
    console.log(e,'eeee')
    let code=e.currentTarget.dataset.code,
      { goodsnum, goodssn, goodscount, count, price, promotionprice } = that.data
    console.log(count,'count')
    console.log(price, 'price')
    price = count * promotionprice
    that.setData({
      showchose: !0,
      anim: 'sizewrap 0.3s',
      price
    })
      that.setData({gobuy:code==2})
  },
  closechose() {
    that.setData({
      showchose: !1,
      anim: ''
    })
  },
  counttap(e) {
    let {  count,data,isconsumer,isretail,cid } = that.data
    if (e.currentTarget.dataset.code == 1) {
      if(count<data.kc){
        count++
      }else{
        wx.showToast({
          title: '商品库存不足',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      if (count > 1) {
        count--
      } else {
        wx.showToast({
          title: '至少添加一件商品',
          icon: 'none',
          duration: 2000
        })
      }
    }
    
    let totalscore = (Number(that.data.mscore)*count),totalprice =(!isconsumer&&isretail=="F"&&cid!=18)?(Number(that.data.mprice)*count).toFixed(2):(Number(that.data.promotionprice)*count).toFixed(2)
    that.setData({
      totalscore,
      totalprice,
      count
    })
   
  },
  sizeconfirm(){
    // wx.navigateTo({
    //   url: '../cart/cart',
    // })
    // that.setData({
    //   showchose: !0,
    //   anim: 'sizewrap 0.7s'
    // })
    let 
      { id,goodsid, count, price, promotionprice,gobuy,carttype } = that.data,paynum='',cartids=wx.getStorageSync('cartids')
        console.log(count, 'count')
        console.log(price, 'price')
        promotionprice =  promotionprice*100
        paynum= count
        goodsid=id
        let data={  paynum,type:'GOODS',goodsid:id }
          if(!gobuy){ 
              api.addcart(data,res=>{
                if(res.data.issuccess == 1){
                  wx.showToast({
                    title: '加入购物车成功',
                    icon: 'none',
                    duration: 2000,
                    success(){
                      if(cartids){
                        console.log('cartids');
                        cartids.push(goodsid)
                        app.badege(cartids)
                        wx.setStorageSync("cartids",cartids)
                      }else{
                        let cartids=[]
                        cartids.push(goodsid)
                        app.badege(cartids)
                        wx.setStorageSync("cartids",cartids)
                      }
                    }
                  })
                  that.setData({
                    showmodal:0
                  })
                }else{
                  wx.showToast({
                    title: '加入购物车失败',
                    icon: 'none',
                    duration: 2000
                  })
                }
                })
          }else{
            wx.navigateTo({
              url: '../confirm/confirm?gobuy=1',
            })
          }
          that.setData({
            showchose: !1,
            anim: '',
          })
        // }
      
   
  },
  // addcart(){
  //   console.log(1)
  //   // api.addshoppingCart
  //   // let { goodsnum  }=that.data
  //   // console.log(goodsnum  ,'name')
  //   that.setData({
  //     showchose: !0,
  //     anim: 'sizewrap 0.7s'
  //   })
  //   let { goodssn }=that.data
  //   console.log(goodssn,'goodssn')
  // },
  collectiongoods(e){
    wx.showLoading({
      title: '加载中',
    })
    let {id,isscore,iscollect}=that.data
    console.log(e.currentTarget.dataset.iscollect,'eeeee')
    api.collectiongoods({ goodsid:id , isscore}, res => {
      // wx.hideLoading({
      //   complete: (res) => {},
      // })
      if (res.data.issuccess == 1) {
        wx.showToast({
          title: iscollect?'取消收藏':'收藏成功',
          icon: 'none',
          success:res=>{
            that.setData({iscollect:!iscollect})
          }
        })
      }   
    })
  },
  toassembledetail(e){
    let { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../assembledetail/assembledetail?id=61',
    })
  },
  // 选择规格
  specitemsel(e){
    let {index,speccont}=e.currentTarget.dataset
    that.setData({indexsel:index,speccont})
  },
  // 登录
  getuserinfo(e){
    console.log(e,'eeee');
    let {origuserinfo}=that.data
    if(!origuserinfo){
      if (e.detail.userInfo){
        let {userInfo} = e.detail;
        // api.updateUser({avatar:userInfo.avatarUrl,name:userInfo.nickName},res=>{
        //   if(res.data.issuccess==1){
        //     that.setData({origuserinfo:e.detail.userInfo,gobuy:true},()=>{
        //       wx.setStorageSync('userinfo', userInfo);
        //       that.setData({
        //         showchose: !0,
        //         anim: 'sizewrap 0.3s',
        //       })
        //     })
        //   }else{
        //     wx.showModal({
        //       title: '提示',
        //       content:'登录失败，请重新登录',
        //       success:function(res){
        //         if(res.confirm){
        //           that.getuserinfo(e)
        //         }
        //       },
        //     })
        //   }
        // })
      }
    }
    // this.getscore(res=>{
    //   wx.setStorageSync('userinfo', userInfo);
    // });
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
      let address = that.data.address;
    if(typeof(address)=='object'){
      that.setData({address:address.province+address.city+address.county+address.street})
    }
  // that.getdetail()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return{
      title: app.logininfo.appletname,
      path: '/pages/goodsDetail/goodsDetail?share=1&id=' + that.data.id
    }
  },
  onShareTimeline: () => {
    let {topimg,name} = that.data
    return {
      title: name,
      imageUrl: topimg,
      query:'id='+that.data.id
    }
  },
})